﻿using System;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Browser;
using Ama.BugTracker.View;
using Gmantis.Controls;

namespace Ama.BugTracker
{
    internal class AppUtils
    {
        /// <summary>
        /// 独立存储区设置
        /// </summary>
        private static IsolatedStorageSettings settings;

        static AppUtils()
        {
            settings = IsolatedStorageSettings.ApplicationSettings;
        }

        /// <summary>
        /// 返回服务端Handler的绝对地址
        /// </summary>
        /// <param name="handlerName">服务端Handler的相对路径</param>
        /// <param name="queryString">查询字符串，不需要添加'?'</param>
        /// <returns></returns>
        internal static Uri CreateHandlerAddress(string handlerName, string queryString = "")
        {
            string absolutePath = HtmlPage.Document.DocumentUri.AbsoluteUri;
            string address = string.Empty;
            if (string.IsNullOrEmpty(queryString))
                address = absolutePath.Substring(0, absolutePath.LastIndexOf('/')) + handlerName;
            else
                address = absolutePath.Substring(0, absolutePath.LastIndexOf('/')) + handlerName + "?" + queryString;

            try
            {
                Uri uri = new Uri(address);
                return uri;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取独立存储区中的应用程序设置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        internal static IsolatedStorageSettings UserConfig
        {
            get { return settings; }
            set { settings = value; }
        }

        internal static void ShowContentLoader()
        {
            GWindow window = new GWindow();
            Loader loader = new Loader();
            window.Height = 100;
            window.Width = 100;
            window.Header = "加载中...";
            window.ShowCloseButton = false;
            window.ShowMaximizeButton = false;
            window.ShowMinimizeButton = false;
            window.Content = loader;
            window.ShowModal();
        }

        internal static T FindParent<T>(FrameworkElement element) where T : FrameworkElement
        {
            FrameworkElement parent = element.Parent as FrameworkElement;
            while ((!(parent is T)) && parent.Parent != null)
            {
                parent = parent.Parent as FrameworkElement;
            }

            if (!typeof(T).IsInstanceOfType(parent) && parent.Parent == null)
                return null;

            return (parent as T);
        }
    }
}
